﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace Sonce.Controls
{
    public partial class ToolbarButton : Button
    {
        //<Button Style="{StaticResource ToolbarButtonStyle}" Content="../Resources/icon_1.png" ToolTipService.ToolTip="tooltip"  />

        #region Members
        private Toolbar parentToolbar;
        #endregion

        #region Constructor
        public ToolbarButton()
            : base()
        {
            this.DefaultStyleKey = typeof(ToolbarButton);
            //this.Style = App.Current.Resources["stylename"] as Style;
        }
        #endregion

        #region Properties
        public Uri Icon
        {
            get
            {
                return (Uri)GetValue(IconProperty);
            }
            set
            {
                SetValue(IconProperty, value);
                if (IconImage != null)
                {
                    IconImage.Source = new BitmapImage(value);
                }
            }
        }

        public Toolbar ParentToolbar
        {
            get
            {
                if (this.parentToolbar == null)
                {
                    object result = Helper.FindParent<Toolbar>(this);
                    if (result != null && result is Toolbar)
                    {
                        this.parentToolbar = result as Toolbar;
                    }
                }
                return this.parentToolbar;
            }
            set
            {
                this.parentToolbar = value;
            }
        }
        #endregion

        #region Dependency
        public static readonly DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(Uri), typeof(ToolbarButton), new PropertyMetadata(null));
        #endregion

        #region Template
        protected FrameworkElement RootElement;
        protected Image IconImage;

        public override void OnApplyTemplate()
        {
            RootElement = (FrameworkElement)GetTemplateChild("RootElement");
            FrameworkElement element = (FrameworkElement)GetTemplateChild("contentPresenter");
            if (element != null && element is Image)
            {
                IconImage = element as Image;
                this.Icon = this.Icon; //Load image
            }
        }
        #endregion

        #region Bubble events
        protected override void OnClick()
        {
            if (this.ParentToolbar != null)
            {
                this.ParentToolbar.OnItemClick(new ToolbarEventArgs(this));
            }
            base.OnClick();
        }

        //internal virtual void OnClick(ToolbarEventArgs e)
        //{
        //    base.OnClick();
        //}
        #endregion
    }
}
